<template>
  <div>
    <div v-if="customerList.length > 0">
      <div style="margin-top: 15px" class="body-box" v-loading="loading">
        <!-- <el-card class="body-box"> -->
        <div class="waterfall-layout">
          <div
            v-for="customer in customerList"
            :key="customer.customerId"
            class="customer-card"
          >
            <div class="card" @click.stop="handleUpdate(customer)">
              <div class="header">
                <h2 class="titel">
                  客户名称: {{ customer.customerName }}
                  <el-dropdown
                    trigger="click"
                    @click.native.stop
                    style="float: right; font-size: 1.2em; color: #0277bd"
                  >
                    <label><i class="el-icon-s-operation"></i></label>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        icon="el-icon-edit-outline"
                        @click.native.stop="openAddTrace(customer)"
                        >跟进</el-dropdown-item
                      >
                      <el-dropdown-item
                        icon="el-icon-s-promotion"
                        @click.native.stop="transferCrmCustomer(customer)"
                        >转移</el-dropdown-item
                      >
                      <el-dropdown-item
                        icon="el-icon-edit"
                        @click.native.stop="handleUpdate(customer)"
                        >修改</el-dropdown-item
                      >
                      <el-dropdown-item
                        icon="el-icon-delete"
                        @click.native.stop="handleDelete(customer)"
                        >删除</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </h2>
                <div class="details">
                  <p>所属区域: {{ customer.region }}</p>
                  <p>
                    所属行业:
                    <dict-tag
                      :options="dict.type.customer_industry"
                      :value="customer.customerIndustry"
                      style="display: inline-block"
                    />
                  </p>
                  <p>负责人: {{ customer.createBy }}</p>
                  <p>客户归属: {{coverGroupData(customer.customerAscription)}}</p>
                </div>
                <div class="total-amount">
                  <p>总合同金额: {{ customer.orderCountAmt }} 元</p>
                </div>
              </div>

              <!-- 90% 进度商机 -->
              <div class="opportunity-category">
                <h3>90% 进度商机</h3>
                <ul
                  class="opportunity-list"
                  v-if="customer.orderDTOMap.progess90"
                >
                  <li
                    v-for="order in customer.orderDTOMap.progess90"
                    :key="order.orderId"
                  >
                    <label>商机名称：{{ order.orderName }}</label>
                    <label>负责人：{{ order.createBy }}</label>
                    <label>金额：{{ order.amount }} 元</label>
                    <label>产品名称：{{ order.productName }}</label>
                  </li>
                </ul>
                <ul class="opportunity-list" v-else>
                  <li>无</li>
                </ul>
              </div>

              <!-- 60% 进度商机 -->
              <div class="opportunity-category">
                <h3>60% 进度商机</h3>
                <ul
                  class="opportunity-list"
                  v-if="customer.orderDTOMap.progess60"
                >
                  <li
                    v-for="order in customer.orderDTOMap.progess60"
                    :key="order.orderId"
                  >
                    <label>商机名称：{{ order.orderName }}</label>
                    <label>负责人：{{ order.createBy }}</label>
                    <label>金额：{{ order.amount }} 元</label>
                    <label>产品名称：{{ order.productName }}</label>
                  </li>
                </ul>
                <ul class="opportunity-list" v-else>
                  <li>无</li>
                </ul>
              </div>

              <!-- 30% 进度商机 -->
              <div class="opportunity-category">
                <h3>30% 进度商机</h3>
                <ul
                  class="opportunity-list"
                  v-if="customer.orderDTOMap.progess30"
                >
                  <li
                    v-for="order in customer.orderDTOMap.progess30"
                    :key="order.orderId"
                  >
                    <label>商机名称：{{ order.orderName }}</label>
                    <label>负责人：{{ order.createBy }}</label>
                    <label>金额：{{ order.amount }} 元</label>
                    <label>产品名称：{{ order.productName }}</label>
                  </li>
                </ul>
                <ul class="opportunity-list" v-else>
                  <li>无</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <!-- </el-card> -->
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!-- 添加或修改客户列对话框 -->
    </div>
    <el-empty :image-size="450" v-else></el-empty>
    <el-drawer
      :title="title"
      direction="rtl"
      :visible.sync="visible"
      size="80%"
      append-to-body
      :wrapperClosable="false"
    >
      <el-card
        class="box-card"
        style="width: 96%; margin-left: 20px; height: 90vh"
      >
        <el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input
                  v-model="form.customerName"
                  placeholder="请输入客户名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户归属" prop="customerAscription">
                <el-select
                  v-model="form.customerAscription"
                  style="width: 100%"
                  placeholder="请选择客户归属"
                  filterable
                >
                  <el-option
                    v-for="dict in getGroupData()"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人" prop="linkman">
                <el-input v-model="form.linkman" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="duty">
                <el-input v-model="form.duty" placeholder="请输入职务" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地区" prop="region">
                <el-cascader
                  v-model="form.region"
                  :options="cityTree"
                  :props="cascaderProps"
                  style="width: 100%"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户行业" prop="customerIndustry">
                <el-select
                  style="width: 100%"
                  v-model="form.customerIndustry"
                  placeholder="请选择客户行业"
                >
                  <el-option
                    v-for="dict in dict.type.customer_industry"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户级别" prop="customerRank">
                <el-select
                  style="width: 100%"
                  v-model="form.customerRank"
                  placeholder="请选择客户级别"
                >
                  <el-option
                    v-for="dict in dict.type.customer_rank"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户类型" prop="customerType">
                <el-select
                  style="width: 100%"
                  v-model="form.customerType"
                  placeholder="请选择客户类型"
                >
                  <el-option
                    v-for="dict in dict.type.crm_customer_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户标签" prop="customerLabel">
                <el-select
                  style="width: 100%"
                  v-model="form.customerLabel"
                  placeholder="请选择客户标签"
                  multiple
                >
                  <el-option
                    v-for="dict in dict.type.crm_customer_label"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户状态" prop="customerStatus">
                <el-select
                  style="width: 100%"
                  v-model="form.customerStatus"
                  placeholder="请选择客户状态"
                >
                  <el-option
                    v-for="dict in dict.type.customer_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="协同人" prop="helpPerson">
                <el-select
                  v-model="form.helpPerson"
                  filterable
                  clearable
                  multiple
                  placeholder="请选择分享人列表"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="dialog-footer">
                <el-button type="primary" @click="submitForm('1')"
                  >提 交</el-button
                >
                <el-button @click="cancel">取 消</el-button>
                <el-button
                  type="info"
                  @click="submitForm('0')"
                  v-if="buttonFlag"
                  >暂 存</el-button
                >
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-card>
    </el-drawer>
    <addTraceInfo ref="addTraceInfo"></addTraceInfo>
    <transferCrmCustomerDialog
      ref="transferCrmCustomerDialog"
      :options="options"
      @closeDialog="getList"
    >
    </transferCrmCustomerDialog>
  </div>
</template>

<script>
import {
  listCustomer,
  getCustomer,
  delCustomer,
  addCustomer,
  updateCustomer,
  getCustomerOne,
} from "@/api/crm/customer";

import {
  getCityTreeAllByParentId,
  selectCityListFromChildToParentId,
} from "@/api/system/city";

import addTraceInfo from "./addTraceInfo.vue";

import transferCrmCustomerDialog from "./transferCrmCustomerDialog.vue";
export default {
  name: "Customer",
  dicts: [
    "customer_industry",
    "crm_customer_type",
    "customer_rank",
    "customer_status",
    "crm_customer_label",
  ],
  components: {
    addTraceInfo,
    transferCrmCustomerDialog,
  },
  props: {
    options: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // total: 0,
      // 客户列表格数据
      customerList: [],
      // 弹出层标题
      title: "添加客户",
      // 是否显示弹出层
      visible: false,
      // 表单参数
      form: {},
      cityTree: [],
      cascaderProps: {
        value: "label", // 选项的ID字段
        label: "label", // 选项的显示字段
        children: "children", // 子节点字段
        checkStrictly: true,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
        ],
        linkman: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
        duty: [{ required: true, message: "职务不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        region: [
          { required: true, message: "地区id不能为空", trigger: "change" },
        ],
        customerIndustry: [
          { required: true, message: "客户行业不能为空", trigger: "change" },
        ],
        customerRank: [
          { required: true, message: "客户级别不能为空", trigger: "change" },
        ],
        customerType: [
          { required: true, message: "客户类型不能为空", trigger: "change" },
        ],
        customerStatus: [
          { required: true, message: "客户状态不能为空", trigger: "change" },
        ],
        userId: [
          { required: true, message: "归属人不能为空", trigger: "blur" },
        ],
        delFlag: [
          { required: true, message: "删除标记不能为空", trigger: "blur" },
        ],
      },
      buttonFlag: false, // 控制暂存按钮
    };
  },

  methods: {
    transferCrmCustomer(row) {
      this.$refs.transferCrmCustomerDialog.open(row.customerId);
    },
    openAddTrace(row) {
      this.$refs.addTraceInfo.open(row);
    },
    open() {
      this.form = {};
      getCustomerOne({ status: "0" }).then((res) => {
        if (res.data) {
          this.form = res.data;
          this.form.region = this.form.region
            ? this.form.region.split(",")
            : null;
          this.form.helpPerson = this.form.helpPerson
            ? this.form.helpPerson.split(",")
            : null;
          this.form.customerLabel = this.form.customerLabel
            ? this.form.customerLabel.split(",")
            : null;
        }
        this.buttonFlag = true;
        this.visible = true;
      });
    },
    getCityTree() {
      getCityTreeAllByParentId(1).then((response) => {
        this.cityTree = response.data;
        this.cityTree = this.moveJiangxiToFirst(this.cityTree)
      });
    },
    /** 查询客户列列表 */
    getList(queryParams = this.queryParams) {
      this.loading = true;
      this.queryParams = queryParams;
      listCustomer(queryParams).then((response) => {
        // this.customerList = response.data;
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getCityTree();
    },
    // 取消按钮
    cancel() {
      this.visible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        customerName: null,
        linkman: null,
        duty: null,
        phone: null,
        region: null,
        customerIndustry: null,
        customerRank: null,
        customerType: null,
        customerLabel: null,
        customerStatus: null,
        helpPerson: null,
        preOwner: null,
        userId: null,
        lastUpdateRecord: null,
        lastFollowupTime: null,
        nextFollowupTime: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.buttonFlag = false;
      this.reset();
      const customerId = row.customerId || this.ids;
      getCustomer(customerId).then((response) => {
        this.form = response.data;
        this.form.region = this.form.region
          ? this.form.region.split(",")
          : null;
        this.form.helpPerson = this.form.helpPerson
          ? this.form.helpPerson.split(",")
          : null;
        this.form.customerLabel = this.form.customerLabel
          ? this.form.customerLabel.split(",")
          : null;
        this.visible = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm(status) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.status = status;

          let obj = { ...this.form };

          obj.region = Array.isArray(this.form.region)
            ? this.form.region.join(",")
            : this.form.region || "";
          obj.helpPerson = Array.isArray(this.form.helpPerson)
            ? this.form.helpPerson.join(",")
            : this.form.helpPerson || "";
          obj.customerLabel = Array.isArray(this.form.customerLabel)
            ? this.form.customerLabel.join(",")
            : this.form.customerLabel || "";

          console.log(obj, this.form);

          if (this.form.customerId != null) {
            updateCustomer(obj).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.visible = false;
              this.getList(this.queryParams);
            });
          } else {
            addCustomer(obj).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.visible = false;
              this.getList(this.queryParams);
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal
        .confirm('是否确认删除客户列编号为"' + customerIds + '"的数据项？')
        .then(function () {
          return delCustomer(customerIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/customer/export",
        {
          ...this.queryParams,
        },
        `customer_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
.list-todo {
  color: white;
  background-color: #1c8ef0;
  padding: 15px;
  border-radius: 10px;
}

.waterfall-layout {
  column-count: 2;
  column-gap: 15px;
}

.customer-card {
  margin-bottom: 15px;
  break-inside: avoid;
}

.body-box {
  max-height: 50vh;
  min-height: 60vh;
  overflow: auto;
}

.pagination-container {
  margin-top: 0;
  height: 20px;
}

/*最外层透明*/
::v-deep .el-table,
::v-deep .el-table__expanded-cell {
  background-color: transparent;
}

/* 表格内背景颜色 */
::v-deep .el-table th,
::v-deep .el-table tr,
::v-deep .el-table td {
  background-color: transparent;
}

.el-table .el-table__row:hover {
  background-color: transparent !important;
  /* 去掉 hover 背景色 */
}
</style>
